import React from 'react';

import styles from './index.less';

import {Upload} from 'antd';
const Dragger = Upload.Dragger;

import {get, postWithFormData} from '../../../logic/api';

export default class QiniuUploadfile extends React.Component {
  
  state = {
    hash:"",
    fileList:[],
    status:'done',
    width:0,
    height:0
  }

  static config = null;
  static myinterval = null;

  async componentWillMount(){
    if (!QiniuUploadfile.config){
      var ret = await get('/auploadfile');
      QiniuUploadfile.config = {
        url:ret.url,
        token:ret.formData.token
      }
    }
    
    this.setState({
      hash:this.props.defaultHash?this.props.defaultHash:"",
      width:this.props.w?this.props.w:480,
    });

  }

  componentWillUnmount(){

  }

  componentWillReceiveProps(n){
    if (n.hash){
      this.setState({
        hash:n.hash
      })
    }else{
      this.setState({
        hash:""
      })
    }
  }

  upload(e){
    this.setState({
      fileList:[e.file]
    })

    if (e.file.status === 'done') {
      var hash = e.file.response.hash;
      this.props.onFetchHash(hash);
      var filename = e.file.name;

      this.setState({
        hash:hash,
        filename:filename,
        fileList:[]
      })
    }
  }

  render(){
    if (!QiniuUploadfile.config){
      return <div/>
    }

    return <div style = {{width:this.state.width}}> 
      <Dragger action = {QiniuUploadfile.config.url} data = {(file)=>{
        return {
          token:QiniuUploadfile.config.token,
          file:file
        }
      }} listType = 'text' fileList = {this.state.fileList} onChange = {(e)=>{this.upload(e)}}>
        {this.state.hash?<img style = {{width:this.state.width-2}} src = {"http://oalpta27j.bkt.clouddn.com/" + this.state.hash}/>:<div>上传图片</div>}
      </Dragger>
    </div>
  }
}
